<template>
  <div class="login-container">
    <div class="left">
      <img :src="require('@/assets/images/login_content_img.png')" alt="" class="login-img">
    </div>
    <div class="right">
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
        <div class="login-title">欢迎登录</div>
        <div class="login-tab">
          <a :class="loginForm.loginType==='1' ? 'active' : ''" class="item" @click="changeLoginType(1)">密码登录</a>
          <a v-if="$config.loginMobile==='1'" :class="loginForm.loginType==='2' ? 'active' : ''" class="item " @click="changeLoginType(2)">短信登录</a>
          <a v-if="$config.loginScan==='1'" :class="loginForm.loginType==='3' ? 'active' : ''" class="item " @click="changeLoginType(3)">扫码登录</a>

        </div>
        <div v-if="loginForm.loginType==='1'">
          <el-form-item prop="username" label="用户名：">
            <el-input ref="username" v-model="loginForm.username" placeholder="请输入用户名" type="text" auto-complete="on" />
          </el-form-item>
          <el-form-item prop="password" label="密码：">
            <el-input :key="passwordType" ref="password" v-model="loginForm.password" show-password type="password" placeholder="请输入密码" auto-complete="on" @keyup.enter.native="handleLogin" />
          </el-form-item>
          <el-form-item prop="verificationCode" label="验证码：" class="flex-main">
            <image-captcha-code ref="captchaCode" v-model="loginForm.verificationCode" />
          </el-form-item>
          <el-button :loading="loading" size="medium" type="primary" style="width: calc(100% - 50px);height: 44px;position: absolute;bottom: 75px;left: 25px;" @click.native.prevent="handleLogin">登录</el-button>

        </div>

        <template v-if="loginForm.loginType==='2'">
          <el-form-item prop="mobile" label="输入手机号：">
            <el-input v-model="loginForm.mobile" placeholder="请输入手机号" maxlength="11" type="text" auto-complete="on" />
          </el-form-item>
          <el-form-item prop="mobileVerificationCode" label="输入验证码：" class="flex-main">
            <verification-code
              v-model="loginForm.mobileVerificationCode"
              :code-device="loginForm.mobile"
              :check="true"
              check-action="userValidateExistByField"
              @checkCode="handleCheckCode" />
          </el-form-item>
          <el-button :loading="loading" size="medium" type="primary" style="width: calc(100% - 50px);height: 44px;position: absolute;bottom: 75px;left: 25px;" @click.native.prevent="handleLogin">登录</el-button>

        </template>
        <template v-if="loginForm.loginType==='3'">
          <div class="qrcode-container">
            <!--<img :src="require('@/assets/images/GetQRImage.png')" alt="">-->
            <div id="qrCode" ref="qrCodeDiv" />
            <template v-if="!isScanLogin">
              <div v-if="!qrCodeIsEffective" class="qrcode-mask" />
              <div v-if="!qrCodeIsEffective" class="qrcode-outdate" style="display: block;">
                <p class="qrcode-status">当前二维码已过期</p>
                <a class="qrcode-refresh" @click="generateLoginQRCode">刷新二维码</a>
              </div>
            </template>
            <template v-if="isScanLogin">
              <div class="qrcode-mask" />
              <div class="qrcode-outdate" style="display: block;">
                <p class="qrcode-status">扫描成功</p>
                <p class="qrcode-status">登录中...</p>
              </div>
            </template>
          </div>
          <div class="qrcode-tip">
            请使用<span class="download-highlight"><a href="https://cdn-chiship.oss-cn-beijing.aliyuncs.com/default/chiship-framework-boot.apk" target="_blank">快速开发框架手机端</a></span>扫码
          </div>
        </template>
        <div class="login-form-footer">
          <div>其他登录方式</div>
          <div class="login-other-type">
            <el-tooltip class="item" effect="dark" content="企业微信" placement="top">
              <el-link :underline="false" @click="handleToBeDeveloped">
                <svg-icon icon-class="loginTypeQYWX" />
              </el-link>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="微信" placement="top">
              <el-link :underline="false" @click="handleToBeDeveloped">
                <svg-icon icon-class="loginTypeWX" />
              </el-link>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="钉钉" placement="top">
              <el-link :underline="false" @click="handleToBeDeveloped">
                <svg-icon icon-class="loginTypeDingDing" />
              </el-link>
            </el-tooltip>
          </div>
          <div style="flex: 1;text-align: right;">
            <el-link :underline="false" style="margin-right:8px" @click="handleGo('password')">忘记密码?</el-link>
            <el-link v-if="$config.registerUser==='1'" :underline="false" @click="handleGo('register')">免费注册</el-link>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { setToken } from '@/utils/auth'
import QRCode from 'qrcodejs2'
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
        mobile: '',
        verificationCode: '',
        mobileVerificationCode: '',
        loginType: '1'
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
        password: [{ required: true, trigger: 'blur', message: '请输入密码' }],
        verificationCode: [
          { required: true, trigger: 'blur', message: '请输入图形验证码' },
          { min: 4, max: 4, message: '请输入4位长度的图形验证码', trigger: 'blur' }
        ],
        mobile: [
          { required: true, trigger: 'blur', message: '请输入手机号' },
          { validator: this.$validate.validateMobile, trigger: 'blur' }

        ],
        mobileVerificationCode: [
          { required: true, trigger: 'blur', message: '请输入手机验证码' },
          { min: 6, max: 6, message: '请输入6位长度的手机验证码', trigger: 'blur' }
        ]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      verificationCodeText: '获取验证码',
      qrCodeIsEffective: true,
      qrCodeImageId: null,
      qrCodeIntervel: null,
      isScanLogin: false
    }
  },
  //
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    },
    'loginForm.loginType': function(val) {
      if (val === '3') {
        this.generateLoginQRCode()
      } else {
        if (this.qrCodeIntervel) {
          clearInterval(this.qrCodeIntervel)
        }
      }
    }
  },
  created() {
    this.loginForm.loginType = '1'
    document.onkeydown = (e) => {
      const key = window.event.keyCode
      if (key === 13) {
        this.handleLogin()
      }
    }
  },
  destroyed() {
    if (this.qrCodeIntervel) {
      clearInterval(this.qrCodeIntervel)
    }
  },
  methods: {
    handleGo(url) {
      this.$router.push({ path: '/' + url })
    },
    generateLoginQRCode() {
      this.qrCodeIsEffective = true
      this.$store.dispatch('generateLoginQRCode').then((res) => {
        this.qrCodeImageId = res.imageId
        document.getElementById('qrCode').innerHTML = ''
        new QRCode(this.$refs.qrCodeDiv, {
          text: res.qrCode,
          width: 160,
          height: 160,
          colorDark: '#333333', // 二维码颜色
          colorLight: '#ffffff', // 二维码背景色
          correctLevel: QRCode.CorrectLevel.L// 容错率，L/M/H
        })
        this.getQRImageStatus()
      }).catch((_) => {
      })
    },

    getQRImageStatus() {
      this.qrCodeIntervel = setInterval(() => {
        if (this.qrCodeImageId) {
          this.$store.dispatch('getQRImageStatus', { imageId: this.qrCodeImageId, loading: false }).then((res) => {
            var code = res.code
            if (code === -1) {
              this.qrCodeIsEffective = false
              if (this.qrCodeIntervel) {
                clearInterval(this.qrCodeIntervel)
              }
            }
            if (code === 1) {
              this.isScanLogin = true
            }
            if (code === 2) {
              setToken(res.token)
              this.$modal.msgSuccess('扫码登陆成功!')
              setTimeout(() => {
                window.location.reload()
              }, 2000)
            }
          }).catch((_) => {
            this.qrCodeIsEffective = false
            if (this.qrCodeIntervel) {
              clearInterval(this.qrCodeIntervel)
            }
          })
        }
      }, 3000)
    },
    changeLoginType(type) {
      this.$refs['loginForm'].clearValidate()
      this.loginForm.loginType = '' + type
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleCheckCode(val) {
      if (val) {
        this.handleLogin()
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          var user = Object.assign({}, this.loginForm)
          if (this.loginForm.loginType === '1') {
            this.$store.dispatch('login', user).then(() => {
              this.$router.push({ path: this.redirect || '/' })
              this.loading = false
            }).catch(() => {
              this.$nextTick(() => {
                this.$refs.captchaCode.getCaptchaCode()
              })
              this.loginForm = {
                ...this.loginForm,
                verificationCode: ''
              }
              this.loading = false
            })
          }
          if (this.loginForm.loginType === '2') {
            this.$store.dispatch('mobileLogin', user).then(() => {
              this.$router.push({ path: this.redirect || '/' })
              this.loading = false
            }).catch(() => {
              this.loading = false
              this.loginForm = {
                ...this.loginForm,
                mobileVerificationCode: ''
              }
            })
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss">
.login-container {
  .el-form-item {
    padding: 0 20px;
    margin-bottom: 11px;
    .el-form-item__label{
      color: #858585;
      font-weight: normal;
    }
  }
  .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap>.el-form-item__label:before, .el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label:before{
    content:''
  }
  .el-input {
    input {
      height: 36px;
      border-radius: 2px;
    }
  }
}
</style>
<style lang="scss" scoped>
.login-container {
  display: flex;
  flex-direction: row;
  height: 100%;
  width: 100%;
  .left{
    width: 500px;
    margin-right: 75px;
    flex: 1;
    img{
      width: 500px;
      height: 500px;
    }
  }
  .right{
    width: 430px;
  }
  .login-form {
    padding: 25px 25px 5px 25px;
    width: 430px;
    height: 570px;
    background: #ffffff;
    border-radius: 8px;
    position: relative;
    .login-title{
      height: 60px;
      line-height: 43px;
      font-size: 28px;
      font-weight: 500;
      color: #5b5b5b;
      letter-spacing: 0.21px;
      border-bottom: 1px solid #ebebeb;
    }

    .login-tab{
      height: 38px;
      border: 1px solid #ebebeb;
      border-radius: 2px;
      margin-top: 10px;
      margin-bottom: 30px;
      display: flex;
      //justify-content: space-between;
      //align-items: center;
      .item {
        position: relative;
        line-height: 36px;
        font-size: 14px;
        width: calc(100% / 3);
        color: #858585;
        text-align: center;
      }
      .item.active  {
        background: #3f8bfd;
        color:#fff;
      }
    }
    .login-form-footer{
      display: flex;
      flex-direction: row;
      color: #858585;
      font-size: 14px;
      align-items: center;
      position: absolute;
      bottom: 15px;
      width: calc(100% - 50px);
      .login-other-type{
        .svg-icon{
          width: 22px;
          height: 22px;
          margin-left: 10px;
        }
      }
    }
    .qrcode-container{
      box-sizing: border-box;
      width: 180px;
      height: 180px;
      position: relative;
      margin: 12px auto 16px;
      text-align: center;
      border: 1px solid #e6e7ea;
      border-radius: 3px;
      #qrCode{
        margin-top: 10px;
        margin-left: 10px;
        width: 160px;
        height: 160px;
      }
      .qrcode-mask {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #fff;
        opacity: .8;
      }
      .qrcode-outdate {
        display: none;
        position: absolute;
        top: 35%;
        left: 0;
        right: 0;
        margin-top: -31px;
        z-index: 10;
        .qrcode-status {
          color: #666;
          font-size: 14px;
        }
        .qrcode-refresh {
          display: block;
          width: 120px;
          height: 30px;
          line-height: 30px;
          border-radius: 60px;
          margin: 11px auto 0;
          background: url() no-repeat;
          background-size: 16px,16px;
          background-color: #3f8bfd;
          background-position: 12px;
          padding-left: 24px;
          font-size: 14px;
          color: #fff;
          cursor: pointer;
        }
      }
    }
    .qrcode-tip{
      text-align: center;
      font-size: 14px;
      color: #91959e;
      .download-highlight{
        color: #3f8bfd;
        padding: 0 5px;
        cursor: pointer;
      }
    }
  }

}
</style>
